import {
  URL,
  get,
  NEWIMAGE_URL,
} from './base_service';
let ossHost = wx.getStorageSync('ossHost')
let signature = wx.getStorageSync('ossSignature')
let ossAccessKeyId = wx.getStorageSync('ossAccessId')
let policy = wx.getStorageSync('ossPolicy')
let ossCallBack = wx.getStorageSync('ossCallBack')
let ossDir = wx.getStorageSync('ossDir')
const securityToken = '';

const chooseAndUploadOSSActicon = (imagePref) => {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        // tempFilePath可以作为img标签的src属性显示图片
        uploadOSSActicon(res.tempFilePaths[0], imagePref)
          .then(imageRes => {
            wx.hideLoading();
            resolve(imageRes)
          }).catch(err => {
            wx.hideLoading();
            reject(err)

          })
      }
    })
  })

}

/**
 * 一次性上传多图封装
 * @param {图片标签str} imagePref 
 * @param {可选图片数量 默认9张} count 
 */
const chooseMultipleOSSImgUploadQiniuAction = (imagePref, count = 9, uploadData = null) => {
  console.log("JJLog:count===:" + count);
  console.log("JJLog:key******===:" + ossAccessKeyId);
  if (uploadData) {
    ossDir = uploadData.dir;
    policy = uploadData.policy;
    ossAccessKeyId = uploadData.accessId;
    signature = uploadData.signature
    ossCallBack = uploadData.callback;
  }
  let imgDataArr = [];
  let mediaType = ['image'];
  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count: count,
      sizeType: ['original', 'compressed'],
      mediaType: mediaType,
      sourceType: ['album', 'camera'],
      success(res) {
        // this.uploadMoreImg(res.tempFilePaths);
        console.log("JJLog:res是：" + JSON.stringify(res));
        let files = res.tempFiles;
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        let successNum = 0;
        let failNum = 0;
        let queue = files.map((file) => {

          return new Promise((resolve, reject) => {
            let expandName = file.tempFilePath.substring(file.tempFilePath.length - 10, file.tempFilePath.length)
            console.log("JJLog:key=======:" + ossAccessKeyId);
            wx.uploadFile({
              url: "https://gc-jb.oss-cn-hangzhou.aliyuncs.com",
              filePath: file.tempFilePath,
              name: 'file',
              formData: {
                'key': ossDir + "/" + new Date().getTime() + expandName,
                policy: policy,
                OSSAccessKeyId: ossAccessKeyId,
                signature: signature,
                callback: ossCallBack
                // 'x-oss-security-token': securityToken // 使用STS签名时必传。
              },
              // header: {
              //   "Content-Type": "multipart/form-data"
              // },
              success: function (res) {
                console.log("JJLog:图片上传成功===：", res);
                console.log("JJLog:图片上传成功：" + JSON.stringify(res));
                try {
                  let resultData = JSON.parse(res.data);
                  let imgData = {
                    imgUrl: resultData.data.filename,
                  }
                  imgDataArr.push(imgData);
                  successNum = successNum + 1;

                  resolve("上传成功")
                } catch (error) {
                  wx.hideLoading();
                  wx.showToast({
                    title: '图片上传异常，请刷新小程序重试',
                    icon: "none",
                    duration: 3000,
                  })

                }

              },
              fail: function (res) {
                failNum = failNum + 1;
                resolve("上传失败");
              }
            });

            // let expandName = file.substring(file.length - 10, file.length)
            // wx.uploadFile({
            //   url: url,
            //   filePath: file,
            //   name: 'file',
            //   formData: {
            //     'token': wx.getStorageSync('qiniu_token'),
            //     'key': imagePref + "/" + new Date().getTime() + expandName,
            //   },
            //   header: {
            //     "Content-Type": "multipart/form-data"
            //   },
            //   success: function (res) {
            //     // resolve(JSON.parse(res.data))
            //     // console.log("JJLog:上传后的图片对象:", res);
            //     let resultData = JSON.parse(res.data);
            //     if (resultData.key) {
            //       resultData.complateUrl = NEWIMAGE_URL + resultData.key
            //       imgDataArr.push(resultData);
            //       successNum = successNum + 1;
            //       resolve("上传成功");
            //     } else {
            //       failNum = failNum + 1;
            //       resolve("上传失败");
            //     }

            //   },
            //   fail: function (res) {
            //     console.log("JJLog:七牛上传图片失败===" + JSON.stringify(res));
            //     failNum = failNum + 1;
            //     resolve("上传失败");
            //   }
            // });

          })
        })

        Promise.all(queue).then(res => {
          wx.hideLoading()
          // console.log("JJLog:res是:" + JSON.stringify(res));
          console.log("JJLog:成功个数:" + successNum);
          console.log("JJLog:失败个数:" + failNum);
          if (failNum == 0) {

          } else {
            wx.showToast({
              title: "上传失败" + failNum + "张图片",
              icon: "none"
            })
          }
          resolve(imgDataArr);

        }).catch(err => {
          reject(err);
        })
      }
    })
  })

}


// 阿里上传图片，单张
const uploadOSSActicon = (filePath, keyPref) => {

  let expandName = filePath.substring(filePath.length - 10, filePath.length)
  return new Promise((resolve, reject) => {
    console.log("JJLogOSS:ossHost是====：" + ossHost);
    console.log("JJLogOSS:ossDir是====：" + (ossDir + "/" + new Date().getTime() + expandName));
    wx.uploadFile({
      url: "https://gc-jb.oss-cn-hangzhou.aliyuncs.com",
      filePath: filePath,
      name: 'file',
      formData: {
        'key': ossDir + "/" + new Date().getTime() + expandName,
        policy,
        OSSAccessKeyId: ossAccessKeyId,
        signature,
        callback: ossCallBack
        // 'x-oss-security-token': securityToken // 使用STS签名时必传。
      },
      // header: {
      //   "Content-Type": "multipart/form-data"
      // },
      success: function (res) {
        console.log("JJLog:图片上传成功：" + JSON.stringify(res));
        try {
          let resultData = JSON.parse(res.data);
          // resultData.complateUrl = NEWIMAGE_URL + resultData.key
          resolve(resultData)
        } catch (error) {
          wx.hideLoading();
          wx.showToast({
            title: '图片上传异常，请刷新小程序重试',
            icon: "none",
            duration: 3000,
          })
        }

      },
      fail: function (res) {
        reject(res)
      }
    });
  })
}





const getUploadToken = () => {
  return new Promise((resolve, reject) => {
    get('/op/upload/sign').
      then((data) => {
        // console.log("JJLog:七牛token是:" + JSON.stringify(data));
        if (data.code == 200) {
          wx.setStorageSync("qiniu_token", data.data)
        } else {
          reject(data)
        }
      }).
      catch((e) => {
        reject(e.message)
      })
  })
}

/** 上传七牛一起 */
const uploadQiniuActicon = (filePath, keyPref) => {

  let url = "https://up-z2.qiniup.com"
  let expandName = filePath.substring(filePath.length - 10, filePath.length)
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      formData: {
        'token': wx.getStorageSync('qiniu_token'),
        'key': keyPref + "/" + new Date().getTime() + expandName,
      },
      header: {
        "Content-Type": "multipart/form-data"
      },
      success: function (res) {
        let resultData = JSON.parse(res.data);
        resultData.complateUrl = NEWIMAGE_URL + resultData.key
        resolve(resultData)
      },
      fail: function (res) {
        reject(res)
      }
    });
  })
}

const chooseAndUploadQiniuActicon = (imagePref) => {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        // tempFilePath可以作为img标签的src属性显示图片
        uploadQiniuActicon(res.tempFilePaths[0], imagePref)
          .then(imageRes => {
            wx.hideLoading();
            resolve(imageRes)
          }).catch(err => {
            wx.hideLoading();
            reject(err)

          })
      }
    })
  })

}
/**
 * 一次性上传多图封装
 * @param {图片标签str} imagePref 
 * @param {可选图片数量 默认9张} count 
 */
const chooseMultipleImgUploadQiniuAction = (imagePref, count = 9) => {
  let url = "https://up-z2.qiniup.com"
  let imgDataArr = [];
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // this.uploadMoreImg(res.tempFilePaths);
        let files = res.tempFilePaths;
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        let successNum = 0;
        let failNum = 0;
        let queue = files.map((file) => {
          return new Promise((resolve, reject) => {
            let expandName = file.substring(file.length - 10, file.length)
            wx.uploadFile({
              url: url,
              filePath: file,
              name: 'file',
              formData: {
                'token': wx.getStorageSync('qiniu_token'),
                'key': imagePref + "/" + new Date().getTime() + expandName,
              },
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (res) {
                // resolve(JSON.parse(res.data))
                // console.log("JJLog:上传后的图片对象:", res);
                let resultData = JSON.parse(res.data);
                if (resultData.key) {
                  resultData.complateUrl = NEWIMAGE_URL + resultData.key
                  imgDataArr.push(resultData);
                  successNum = successNum + 1;
                  resolve("上传成功");
                } else {
                  failNum = failNum + 1;
                  resolve("上传失败");
                }

              },
              fail: function (res) {
                console.log("JJLog:七牛上传图片失败===" + JSON.stringify(res));
                failNum = failNum + 1;
                resolve("上传失败");
              }
            });

          })
        })

        Promise.all(queue).then(res => {
          wx.hideLoading()
          // console.log("JJLog:res是:" + JSON.stringify(res));
          console.log("JJLog:成功个数:" + successNum);
          console.log("JJLog:失败个数:" + failNum);
          if (failNum == 0) {

          } else {
            wx.showToast({
              title: "上传失败" + failNum + "张图片",
              icon: "none"
            })
          }
          resolve(imgDataArr);

        }).catch(err => {
          reject(err);
        })
      }
    })
  })

}

/**
 * 临时封装的上传视频
 * @param {*} videoPref 
 */
const chooseAndUploadQiniuVideoAction = (videoPref) => {

  return new Promise((resolve, reject) => {

    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      // compressed: false,
      // maxDuration: 60,
      camera: 'back',
      success(res) {
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        console.log("当前传的视频是:" + JSON.stringify(res));

        uploadQiniuActicon(res.tempFilePath, videoPref)
          .then(imageRes => {
            wx.hideLoading();
            console.log(imageRes)
            resolve(imageRes)
          }).catch(err => {
            wx.hideLoading();
            reject(err)

          })

      },
      fail(err) {
        console.log(err);
      }
    })

  })

}




const uploadAction = (count, id, info) => {
  var that = this;
  let url = URL + "/recommend_customers/" + id + "/change"
  wx.chooseImage({
    count: count, //最多可以选择的图片总数
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths;
      //启动上传等待中...
      wx.showToast({
        title: '正在上传...',
        icon: 'loading',
        mask: true,
        duration: 10000
      })
      var uploadImgCount = 0;
      for (var i = 0, h = tempFilePaths.length; i < h; i++) {
        wx.uploadFile({
          url: url,
          filePath: tempFilePaths[i],
          name: 'images',
          formData: {
            'id': id,
            'totalPrice': info.totalPrice,
            'status': info.status,
          },
          header: {
            "Content-Type": "multipart/form-data"
          },
          success: function (res) {
            console.log("res: ", res.data)
            uploadImgCount++;


            //如果是最后一张,则隐藏等待中
            if (uploadImgCount == tempFilePaths.length) {
              wx.hideToast();
            }
          },
          fail: function (res) {
            wx.hideToast();
            wx.showModal({
              title: '错误提示',
              content: '上传图片失败',
              showCancel: false,
              success: function (res) { }
            })
          }
        });
      }
    }
  });
}
const parseImageUrl = (url) => {
  return `${NEWIMAGE_URL}${url}`
}

module.exports = {
  uploadAction,
  getUploadToken,
  uploadQiniuActicon,
  chooseAndUploadQiniuActicon,
  parseImageUrl,
  chooseMultipleImgUploadQiniuAction,
  chooseAndUploadQiniuVideoAction,
  uploadOSSActicon,
  chooseAndUploadOSSActicon,
  chooseMultipleOSSImgUploadQiniuAction
}